import { Toolkit } from "../Framework/scripts/Toolkit";
import Watcher from "../Framework/scripts/Watcher";

const { ccclass, property } = cc._decorator;

@ccclass
export default class EffectMgr extends cc.Component {

    //消除特效
    static readonly PLAY_CLEAN_ANIM = 'PLAY_CLEAN_ANIM';
    cleanAnims: cc.Node[] = [];

    //TODO other effect

    start() {
        setTimeout(() => {
            this.loadPref();
        }, 400);
        Watcher.on(EffectMgr.PLAY_CLEAN_ANIM, this, this.playClean);
    }

    loadPref() {
        const cleanAnims = this.cleanAnims;

        cc.loader.loadRes('pref/Clean_anim', cc.Prefab, (error: Error, resource: any) => {
            if (!error) {
                for (let i = 0; i < 3; i++) {
                    cleanAnims.push(cc.instantiate(resource));
                }
                cleanAnims[0].getComponent(cc.Animation).on(cc.Animation.EventType.FINISHED, this.onCleanComplete, this);
            }
            else {
                Toolkit.logFailure(error);
            }
        });


        //TODO 其它需要加载的特效


    }


    _cleanCallback = null;
    /**
     * 消除动画
     * @param posArr 含世界坐标
     */
    playClean(posArr: cc.Node[], cb: Function = null) {

        for (let i = 0; i < this.cleanAnims.length; i++) {

            let pos = posArr[i].convertToWorldSpaceAR(cc.Vec2.ZERO);
            this.node.convertToNodeSpaceAR(pos, pos);
            this.cleanAnims[i].setParent(this.node);
            this.cleanAnims[i].setPosition(pos);
        }

        this.cleanAnims.forEach(element => {
            element.getComponent(cc.Animation).play('clean_once');
        });

        this._cleanCallback = cb;
    }

    /**
     * 消除动画结束时回调
     */
    onCleanComplete() {
        this.cleanAnims.forEach(element => {
            element.removeFromParent();
        });
        this._cleanCallback && this._cleanCallback();
    }

}
